#!/usr/bin/
# -*- coding: utf-8 -*-
import hmac
import hashlib
import urllib
import urllib.parse
import json
import win32con
import win32gui
import pyautogui
import time
import base64
import requests


class dingtalkMessage(object):
    def __init__(self):
        self.times = None
        self.sign = None
        self.response = None

    def weather(self):
        url = 'http://t.weather.sojson.com/api/weather/city/101280601'
        r = requests.get(url)
        response_data = r.json()
        result = json.dumps(response_data, sort_keys=True, indent=2, ensure_ascii=False)
        r = json.loads(result)
        self.response = r['cityInfo']['city'] + '\n' + r['time'] + '\n' + r['data']['forecast'][0][
            'type'] + '\n' + r['data']['forecast'][0]['high'] + '\n' + r['data']['forecast'][0][
                            'low'] + '\n' + r['data']['forecast'][0]['notice']

    def signature(self):
        self.times = int(round(time.time() * 1000))
        secret = 'SEC12808f1d15e1e4722ab587c65ff28edaf00962701d3116cc698f1add5e820208'
        secret_enc = str(secret).encode('utf-8')
        string_to_sign = '{}\n{}'.format(self.times, secret)
        string_to_sign_enc = str(string_to_sign).encode('utf-8')
        hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
        self.sign = urllib.parse.quote(base64.b64encode(hmac_code))

    def markDown(self):
        pic = dt.uploadJpg()
        url = 'https://oapi.dingtalk.com/robot/send?access_token=6d9595d480610e650bd7462de5525249c44ffb0c7f47f66346ed44f8ed89bc20' + '&timestamp=' + str(
            self.times) + '&sign=' + self.sign
        data_markdown = {
            "msgtype": "markdown",
            "markdown": {
                "title": "深圳天气",
                "text": f"![avatar]({pic}){self.response}"
            },
            "at": {
                "atMobiles": [
                    "17620533205",
                    "11111111111"
                ],
                "isAtAll": True
            }
        }
        headers = {
            'Content-Type': 'application/json'
        }
        r1 = requests.post(url, data=json.dumps(data_markdown), headers=headers)
        # r2 = r1.json()
        # print(r2)
        print("推送成功")

    def dataLink(self):
        pic = dt.uploadJpg()
        url = 'https://oapi.dingtalk.com/robot/send?access_token=6d9595d480610e650bd7462de5525249c44ffb0c7f47f66346ed44f8ed89bc20' + '&timestamp=' + str(
            self.times) + '&sign=' + self.sign
        data_link = {
            "msgtype": "link",
            "link": {
                "text": self.response,
                "title": "深圳天气",
                "picUrl": pic,
                "messageUrl": "http://www.weather.com.cn/weather/101280601.shtml"
            }
        }
        headers = {
            'Content-Type': 'application/json'
        }
        r1 = requests.post(url, data=json.dumps(data_link), headers=headers)
        # r2 = r1.json()
        # print(r2)
        print("推送成功")

    @staticmethod
    def screenshot():
        wdname = '工作簿 - Google Chrome'
        hwnd = win32gui.FindWindow(None, wdname)
        win32gui.SetForegroundWindow(hwnd)
        win32gui.ShowWindow(hwnd, win32con.SW_MAXIMIZE)
        pyautogui.hotkey("F11")
        time.sleep(1)
        pyautogui.screenshot(r"C:\Users\Administrator\Desktop\screenshot.jpg")

    @staticmethod
    def uploadJpg():
        dt.screenshot()
        url = "https://sm.ms/api/v2/upload?inajax=1"
        apiToken = "0Gff5VNOQv9XcCVZjfOt2kllsshVV7OH"
        headers = {
            "content-type": "multipart/form-data ",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 "
                          "Safari/537.36",
            "Authorization": apiToken
        }
        files = {
            'smfile': open(r"C:\Users\Administrator\Desktop\screenshot.jpg", "rb"),  # => 用name指定文件
            'Content-Disposition': 'form-data',
            'Content-Type': 'image/jpeg',
            'filename': 'screenshot.jpg'
        }
        r1 = requests.post(url, files=files)  # => 注意这里，参数名是 files
        r2 = r1.json()
        r3 = json.dumps(r2, ensure_ascii=False, indent=4)
        picUrl = r2['data']['url']
        # print(r3)
        # print(picUrl)
        return picUrl


while True:
    dt = dingtalkMessage()
    t1 = str(time.strftime("%H:%M:%S"))
    t2 = str(time.strftime("08:00:00"))
    t3 = str(time.strftime("20:00:00"))
    time.sleep(1)
    print(t1)
    if t1 == t2 or t1 == t3:
        dt.weather()
        dt.signature()
        dt.dataLink()
        dt.markDown()
    else:
        continue
